package com.suns.service;

import com.google.common.base.Preconditions;
import com.suns.beans.PageQuery;
import com.suns.beans.PageResult;
import com.suns.dao.SysUserMapper;
import com.suns.exception.ParamException;
import com.suns.model.SysDept;
import com.suns.model.SysUser;
import com.suns.param.UserParam;
import com.suns.util.BeanValidator;
import com.suns.util.LevelUtil;
import com.suns.util.MD5Util;
import com.suns.util.PasswordUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    public PageResult<SysUser> getPageByDeptId(int deptId, PageQuery page){
        BeanValidator.check(page);
        int count = sysUserMapper.countByDeptId(deptId);
        if (count > 0) {
            List<SysUser> list = sysUserMapper.getPageByDeptId(deptId, page);
            return PageResult.<SysUser>builder().total(count).data(list).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    public SysUser findByKeyword(String keyword){
        return sysUserMapper.findByKeyword(keyword);
    }

    /**
     * 管理员修改用户的一些信息 ？？？？
     * @param param
     */
    public void update(UserParam param){
        BeanValidator.check(param);
        if (checkEmailExist(param.getMail(), param.getId())) {
            throw new ParamException("邮箱已被占用");
        }
        if (checkTelephoneExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用");
        }

        // 获取更新前的部门数据 old
        SysUser beforeUser = sysUserMapper.selectByPrimaryKey(param.getId());
        // 判断更新前的部门是否为空，为空则抛出异常
        Preconditions.checkNotNull(beforeUser, "待更新的部门不存在");

        // build更新后的数据
        SysUser afterUser = SysUser.builder().id(param.getId()).username(param.getUsername()).telephone(param.getTelephone())
                .mail(param.getMail()).deptId(param.getDeptId()).status(param.getStatus())
                .remark(param.getRemark()).build();
        // 需计算level，使用自定义level工具类
        afterUser.setOperator("system-update"); // TODO
        afterUser.setOperateIp("127.0.0.1"); // TODO
        afterUser.setOperateTime(new Date());

        sysUserMapper.updateByPrimaryKeySelective(afterUser);
    }

    /**
     * 校验电话是否存在
     * @param telephone
     * @param id
     * @return
     */
    public boolean checkTelephoneExist(String telephone, Integer id){
        return sysUserMapper.countByTelephone(telephone, id) > 0;
    }

    /**
     * 校验邮箱是否存在
     * @param mail
     * @param id
     * @return
     */
    public boolean checkEmailExist(String mail, Integer id) {
        return sysUserMapper.countByMail(mail, id) > 0;
    }

    /**
     * 添加用户
     * @param param
     */
    public void save(UserParam param){
        BeanValidator.check(param);
        if (checkEmailExist(param.getMail(), param.getId())) {
            throw new ParamException("邮箱已被占用");
        }
        if (checkTelephoneExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用");
        }

        String password = PasswordUtil.randomPassword();
        // TODO
        password = "123456";
        // 不能明文存储，需加密
        String encryptedPassword = MD5Util.encrypt(password);
        // 组装当前用户
        SysUser user=SysUser.builder().username(param.getUsername()).telephone(param.getTelephone())
                .mail(param.getMail()).password(encryptedPassword).deptId(param.getDeptId())
                .status(param.getStatus()).remark(param.getRemark()).build();

        user.setOperator("system"); // TODO
        user.setOperateIp("127.0.0.1"); // TODO
        user.setOperateTime(new Date());

        // TODO: sendEmail  先发送email再更新

        sysUserMapper.insertSelective(user);
    }


}
